<?php

class LoginForm extends CFormModel
{
    public $nameOrEmail;
    public $password;
    public $rememberMe=1;
    public $user;

    public function rules()
    {
        return array(
            array('nameOrEmail, password', 'required'),
            array('password', 'authenticate'),
            array('rememberMe', 'in', 'range'=>array(0,1)),
        );
    }

    public function attributeLabels()
    {
        return array(
            'nameOrEmail'=>'用户名',
            'password'=>'密码',
            'rememberMe'=>'下次自动登录',
        );
    }

    public function authenticate($attribute,$params)
    {
        if(!$this->hasErrors())  // we only want to authenticate when no input errors
        {
            if(strstr($this->nameOrEmail, '@')) {  //login by email address
                $this->user=User::loadObjectByEmail($this->nameOrEmail, array('email','password'));
                if(!$this->user){
                    $this->addError('nameOrEmail','邮件地址或密码不正确');
                    return false;
                }
            }
            else {
                $this->user=User::loadObjectByName($this->nameOrEmail, array('name','password'));
                if(!$this->user){
                    $this->addError('nameOrEmail','用户名或密码不正确');
                    return false;
                }
            }

            if($this->user->password!=md5($this->password)){
                $this->addError('password', '用户名或密码不正确');
                return false;
            }

            return true;
        }
    }
}

class LoginAction extends CAction
{
    public function run()
    {
        $form=new LoginForm;
        if(isset($_POST['LoginForm']))
        {
            $form->attributes=$_POST['LoginForm'];
            if($form->validate()) {
                
                $user=$form->user;
                $identity=new UserIdentity($user->id, $user->name, $user->password);
                $duration=$form->rememberMe ? 3600*24*30 : 0;
                Yii::app()->user->login($identity, $duration);
                
                $user->lastLoginIp=Yii::app()->request->userHostAddress;
                $user->lastLoginTime=time();
                
                User::saveObject($user,array('lastLoginIp', 'lastLoginTime'));                

                $this->controller->redirect(Yii::app()->user->returnUrl);
            }
        }

        $this->controller->render('login',array('form'=>$form));
    }
}

?>